package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Remind;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.Train;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.core.service.com.TrainService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/19.
 */
@Controller
@RequestMapping(value = "/com/train")
public class TrainController extends BaseController {
    private static final long serialVersionUID = 8550684716286542940L;

    @Autowired
    private TrainService trainService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private UserService userService;
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private RemindService remindService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> trainDictItems = getDictItems(user,"trainType");
        if (StringUtils.isNotEmpty(keyId)){
            Train train=trainService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("train", train);
        }
        model.addAttribute("trainDictItems",trainDictItems);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/train_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            Train train=trainService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("train", train);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/train_read";
    }

    /**
     * 保存Model
     */
    public Train saveModel(User user, String keyId, String theme, String trainDictItemId, String content, String cycleStart,
                           String cycleEnd, String lecturer, String userIds) throws ParseException {
        Train train=null;
        if(StringUtils.isBlank(keyId)){
            train=new Train();
            train.setCreater(user);
            train.setCompany(user.getCompany());
            train.setName("培训");
        }else{
            train=trainService.get(keyId);
        }
        if(StringUtils.isNotEmpty(theme)){
            train.setTheme(theme);
        }
        if(StringUtils.isNotEmpty(trainDictItemId)){
            train.setType(dictItemService.get(trainDictItemId));
        }
        if(StringUtils.isNotEmpty(content)){
            train.setContent(content);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(cycleStart)){
            train.setCycleStart(sdf.parse(cycleStart));
        }
        if(StringUtils.isNotEmpty(cycleEnd)){
            train.setCycleEnd(sdf.parse(cycleEnd));
        }
        if(StringUtils.isNotEmpty(lecturer)){
            train.setLecturer(lecturer);
        }
        if(StringUtils.isNotEmpty(userIds)){
            List<User> userList=new ArrayList<User>();
            for(String id:userIds.split(",")){
                userList.add(userService.get(id));
            }
            train.setJoinUsers(userList);
        }

        return train;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam (required = false) String keyId,
                       String theme,
                       String trainDictItemId,
                       String content,
                       String cycleStart,
                       String cycleEnd,
                       String lecturer,
                       String userIds) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Train train=saveModel(user,keyId,theme,trainDictItemId,content,cycleStart,cycleEnd,lecturer,userIds);

        if(StringUtils.isNotEmpty(keyId)){
            trainService.update(train);
            rMap.put("message", "更新成功");
        } else {
            trainService.save(train, "com.fz.us.oa.core.entity.com.Train");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam (required = false) String keyId,
                         String theme,
                         String trainDictItemId,
                         String content,
                         String cycleStart,
                         String cycleEnd,
                         String lecturer,
                         String userIds,
                         String curDutyId,
                         String comment) throws ParseException {

        Map<String, Object> rMap = new HashMap<String, Object>();
        Train train=saveModel(user,keyId,theme,trainDictItemId,content,cycleStart,cycleEnd,lecturer,userIds);

        if (StringUtils.isNotEmpty(keyId)) {
            trainService.approve(train, dutyService.get(curDutyId), comment);
        } else {
            trainService.commit(train, "com.fz.us.oa.core.entity.com.Train", dutyService.get(curDutyId));
        }

        if(train.getProcessState().name().equals("Finished")){
            doFinished(train);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment, String parentId){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Train train=trainService.get(keyId);
        trainService.approve(train, dutyService.get(curDutyId), comment);

        //归档后发送提醒
        if(train.getProcessState().name().equals("Finished")){
            doFinished(train);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(Train train){
        for(User joinUser:train.getJoinUsers()){
            Remind remind = new Remind();
            remind.setUser(joinUser);
            remind.setBussinessKey("train");
            remind.setKeyId(train.getId());
            remind.setContent("您有一次培训计划，请查看");
            remindService.save(remind);
        }
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Train train=trainService.get(keyId);
            trainService.back(train, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Train train=trainService.get(keyId);
            trainService.deny(train, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    String parentId,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //申请中
                params.put("finish", false);
                searchResult = trainService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Train", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //培训中
                params.put("finish", false);
                searchResult = trainService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Train", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //已完成
                params.put("finish", true);
                searchResult = trainService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Train", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }
        }else{
            //所有单子
            searchResult = trainService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.Train",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<Train> trainList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        if(StringUtils.isNotEmpty(parentId)){
            User thisUser=personnelInfoService.get(parentId).getUser();
            for(Train train: trainList){
                if(train.getJoinUsers().contains(thisUser)){
                    rMap = new HashMap<String, Object>();
                    rMap.put("id", StringUtils.isEmpty(train.getId())?"":train.getId());
                    rMap.put("theme", StringUtils.isEmpty(train.getTheme())?"":train.getTheme());
                    rMap.put("type", train.getType()==null?"":train.getType().getName());
                    rMap.put("date", "从"+DataUtil.DateToString(train.getCycleStart(),"yyyy-MM-dd")+"到"+DataUtil.DateToString(train.getCycleEnd(),"yyyy-MM-dd"));
                    rMap.put("createTime", DataUtil.DateToString(train.getCreateTime()));
                    if(train.getFinishState()==1){
                        rMap.put("state", "已完成");
                    }else if(train.getFinishState()==2){
                        rMap.put("state", "已取消");
                    }else{
                        rMap.put("state", train.getProcessState().value());
                    }
                    dataRows.add(rMap);
                }
            }
        }else{
            for(Train train: trainList){
                rMap = new HashMap<String, Object>();
                rMap.put("id", StringUtils.isEmpty(train.getId())?"":train.getId());
                rMap.put("theme", StringUtils.isEmpty(train.getTheme())?"":train.getTheme());
                rMap.put("type", train.getType()==null?"":train.getType().getName());
                rMap.put("date", "从"+DataUtil.DateToString(train.getCycleStart(),"yyyy-MM-dd")+"到"+DataUtil.DateToString(train.getCycleEnd(),"yyyy-MM-dd"));
                rMap.put("createTime", DataUtil.DateToString(train.getCreateTime()));
                if(train.getFinishState()==1){
                    rMap.put("state", "已完成");
                }else if(train.getFinishState()==2){
                    rMap.put("state", "已取消");
                }else{
                    rMap.put("state", train.getProcessState().value());
                }
                dataRows.add(rMap);
            }
        }


        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 从人事信息进入培训记录
     */
    @RequestMapping(value = "toList",method = RequestMethod.GET,produces = MediaType.TEXT_HTML_VALUE)
    public String toList(Model model,String parentId){
        model.addAttribute("parentId", parentId);

        return "/main/menu/com/train_in";
    }

    /**
     * 验证身份
     */
    @RequestMapping(value = "checkUser/{keyId}",method = RequestMethod.GET)
    public Object checkUser(@CurrentUser User user,
                            @PathVariable String keyId){
        Train train=trainService.get(keyId);
        if(!user.getId().equals(train.getCreater().getId())){
            return ajaxJson(resultService.fail("您不是此培训的申请人"));
        }else{
            return ajaxJson(resultService.success("身份通过"));
        }
    }

    /**
     * 培训完成对话框
     */
    @RequestMapping(value = "finish/{keyId}",method = RequestMethod.GET,produces = MediaType.TEXT_HTML_VALUE)
    public Object finish(@CurrentUser User user, Model model,
                         @PathVariable String keyId){

        model.addAttribute("keyId", keyId);

        return "/com/train_finish_dialog";
    }

    /**
     * 保存培训完成培训总结
     */
    @RequestMapping(value = "saveFinish/{keyId}",method = RequestMethod.POST)
    public Object saveFinish(@PathVariable String keyId, String summary){
        Train train=trainService.get(keyId);
        if(StringUtils.isNotEmpty(summary)){
            train.setSummary(summary);
        }
        train.setFinish(true);
        train.setFinishState(1);

        return ajaxJson(trainService.saveEntity(train));
    }

    /**
     * 培训取消对话框
     */
    @RequestMapping(value = "cancel/{keyId}",method = RequestMethod.GET,produces = MediaType.TEXT_HTML_VALUE)
    public Object cancel(@CurrentUser User user, Model model,
                         @PathVariable String keyId){

        model.addAttribute("keyId", keyId);

        return "/com/train_cancel_dialog";
    }

    /**
     * 保存培训取消取消原因
     */
    @RequestMapping(value = "saveCancel/{keyId}",method = RequestMethod.POST)
    public Object saveCancel(@PathVariable String keyId, String cancelReason){
        Train train=trainService.get(keyId);
        if(StringUtils.isNotEmpty(cancelReason)){
            train.setCancelReason(cancelReason);
        }
        train.setFinish(true);
        train.setFinishState(2);

        //发送提醒
        for(User joinUser:train.getJoinUsers()){
            Remind remind = new Remind();
            remind.setUser(joinUser);
            remind.setBussinessKey("train");
            remind.setKeyId(keyId);
            remind.setContent("您有一次培训已取消，请查看");
            remindService.save(remind);
        }

        return ajaxJson(trainService.saveEntity(train));
    }

}
